HttpURLConnection是一個輕量的HTTP客户端,可以進行HTTP的連線操作,使用上簡單,擴展也容易。
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
result_txt = findViewById(R.id.result_txt);
//開啟線程,進行HttpURLConnection操作
thread = new Thread(new Runnable() {
@Override
public void run() {
try {
//傳入api網址
getPost("https://jsonplaceholder.typicode.com/posts/1");
} catch (IOException e) {
Log.e("error", "ErrorMsg: "+e.getMessage());
e.printStackTrace();
}
}
});
thread.start();
}
private void getPost(String path) throws IOException {
//API網址
URL url = new URL(path);
StringBuilder result = new StringBuilder();
//獲取與URL的連線
httpURLConnection = (HttpURLConnection) url.openConnection();
//設定連線超時時間
httpURLConnection.setConnectTimeout(5000);
//設定請求類型
httpURLConnection.setRequestMethod("GET");
//判斷如果請求結果不為成功的話
if(httpURLConnection.getResponseCode()!=200){
Toast.makeText(this,"連線失敗",Toast.LENGTH_SHORT).show();
}
//獲取連線的輸入流(結果都在裡面)
InputStream inputStream = httpURLConnection.getInputStream();
//使用BufferReader讀出
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream));
//用來暫時存取結果
String resultString;
//當還有資料時繼續讀取
while ((resultString = bufferedReader.readLine()) != null){
result.append("\n"+resultString);
}
Log.d("回傳結果", "getPost: "+result);
//因為這為ui操作,需回到UI線程。
runOnUiThread(()->{
result_txt.setText(result.toString());
});
//斷線
httpURLConnection.disconnect();
}
這樣就透過HttpURLConnection完成簡單的連線和讀取操作,不過這個方法需要自己開啟線程,後續將會教各位好用的第三方套件,都是以此為基礎延生的好用套件,各位可以期待一下~